package com.qcloud;

import com.alibaba.fastjson.JSON;
import com.health.mapp.utils.StringUtils;
import com.qcloud.domain.LiveConfigDO;
import com.qcloud.listener.AbstractLiveMsgListener;
import com.qcloud.listener.QCloudMsgListener;
import com.qcloud.listener.QCloudMsgResponse;
import com.qcloud.utils.HttpClientUtil;
import org.apache.commons.codec.digest.DigestUtils;

import java.util.Map;

/**
 *
 * Created by YYY on 2017/7/9.
 */
public class DefaultQCloudClient implements QCloudClient{

    private LiveConfigDO liveConfig;

    public DefaultQCloudClient(LiveConfigDO liveConfig) {
        this.liveConfig = liveConfig;
    }

    private <T extends QCloudResponse> Map<String, Object> getLiveRequestParams(QCloudRequest<T> request){
        String timestamp = Long.toHexString(System.currentTimeMillis()/1000);
        Map<String, Object> params = request.getTextParams();
        params.put("cmd", liveConfig.getSdkAppId());//即直播APPID，用于区分不同客户的身份
        params.put("t", timestamp);
        String sign = DigestUtils.md5Hex(liveConfig.getKey()+timestamp);
        params.put("sign", sign);
        params.putAll(request.getTextParams());
        return params;
    }

    @Override
    public <T extends QCloudResponse> T execute(QCloudRequest<T> request) throws QCloudException {
        String url = null;
        if(request.getService() == QCloudBiz.LIVE){
            url = request.getRequestUrl();
        }else{
            throw new QCloudException("Unsupport QCloud Service Request.");
        }
        try {
            String res = null;
            if(request.getRequestMethod() == RequestMethod.POST){
                res = HttpClientUtil.post(url, request.getTextParams());
            }else if(request.getRequestMethod() == RequestMethod.GET){
                Map<String, Object> params = getLiveRequestParams(request);
                res = HttpClientUtil.get(url,params);
            }
            if(!StringUtils.isBlank(res)){
                return JSON.parseObject(res, request.getResponseClass());
            }
        } catch (Throwable e) {
            throw new QCloudException(e);
        }
        throw new QCloudException("Request qcloud response null.");
    }

    @Override
    public QCloudMsgResponse doMsgProcess(QCloudMsgListener msgListener, String msgBody, Map<String, Object> urlParams) throws QCloudException {
        if(msgListener instanceof AbstractLiveMsgListener){
            return msgListener.doProcess(msgBody,urlParams, liveConfig.getKey());
        }
        throw new QCloudException("UnSupported QCloudMsgListener,msgListener="+msgListener);
    }

    public void setLiveConfig(LiveConfigDO liveConfig) {
        this.liveConfig = liveConfig;
    }
}
